package concurrent.producerconsumer;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * Author: Jason Wu
 * Date  : 2013-12-19
 */
public class Consumer implements Runnable {
    private DynamicThreadPool dynamicThreadPool;
    private final LinkedBlockingQueue<Task> queue;

    public Consumer(LinkedBlockingQueue<Task> queue, DynamicThreadPool dynamicThreadPool) {
        this.queue = queue;
        this.dynamicThreadPool = dynamicThreadPool;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (queue){
                if(queue.isEmpty()){
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                dynamicThreadPool.execute(queue.poll());
            }
        }
    }
}
